<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<BulletOnRails4NET.Controllers.GridHelper>" %>

<%@ Import Namespace="BulletOnRails4NET.Controllers" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    List
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <link rel="stylesheet" type="text/css" media="screen" title="basic" href="<%= PathResolver.GetSiteRoot() + "content/themes/basic/grid.css" %>" />
    <link type="text/css" rel="stylesheet" href="<%= PathResolver.GetSiteRoot() + "Scripts/css/jquery.flexbox.css" %>" />  
    
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>

    <script type="text/javascript">
    var clear_fields_on_new, col_names, col_model, details_form_options,
        edit_fields_model, possible_values_for_assocs;
        
        
        function create_html_for_text_field(field_id, field_name, width)
        {
            return "<input id=\"" + field_id + 
            "\" name=\"" + field_name + 
            "\" width=\"" + width + "px\" />";
        }
        
        function create_html_for_cmb(field_id, field_name, id_label_pairs)
        {
            //Sort the pairs
            id_label_pairs = id_label_pairs.sort(function(a,b){ 
            if (a.Label == b.Label)
                return 0;
            else if (a.Label < b.Label)
                return -1;
            else if (a.Label > b.Label)
                return 1; }
             );
            
            html_txt = "<select id=\"" + field_id + 
            "\" name=\"" + field_name + 
            "\" >";
            html_txt += '<option value=""></option>';
            $.each(id_label_pairs, function(index, id_label_pair) {
                html_txt += '<option value="'+ id_label_pair.ID + '">' + id_label_pair.Label + '</option>';
            });
            html_txt += '</select>';
            return html_txt
        }
        
        google.load("jquery", "1");

        google.setOnLoadCallback(function() {

            jqGridInclude();
            clear_fields_on_new = <%= Model.clear_fields_on_new.ToString().ToLower() %>;
            $.getJSON("<%= Model.assoc_data_url %>", null, function(data) {
                possible_values_for_assocs =  data;
            });
            
            $.getJSON("<%= Model.grid_metadata_url %>", null, function(data) {
                col_names = data.colNames;
                col_model = data.colModel;
                edit_fields_model = data.editFieldsModel;
                setup_grid();
            });
            
                        
        });

        function reset_grid_and_form(message)
        {
                alert(message);
                $("#list").trigger("reloadGrid");
                if (clear_fields_on_new)
                    $("#details_form").resetForm();
        }
        
        function setup_grid() {
            //Set up the grid
            $("#list").jqGrid({
                url: '<%= Model.grid_data_url %>' ,
            datatype: 'json',
            myType: 'GET',
            colNames: col_names,
            colModel: col_model,
            pager: $('#pager'),
            rowNum: <%= Model.grid_rows_per_page %>,
            rowList: [5, 10, 15],
            sortname: 'id',
            sortorder: 'desc',
            viewrecords: true,
            multiselect: true,
            imgpath: '<%= PathResolver.GetSiteRoot() + "content/themes/basic/images" %>',
            caption: '<%= Model.grid_title %>',
            onSelectRow: show_record_in_form

        });
        //Add the edit form at the top of the table
        txt_fields = "<fieldset><legend>Fields</legend>";
        for(var col_idx = 0; col_idx < edit_fields_model.length; col_idx++)
        {
            curr_col_model = edit_fields_model[col_idx];
            txt_fields += "<div class=\"edit_form_field\"><label>" + curr_col_model.name + "</label>";
            if (possible_values_for_assocs[curr_col_model.index] == null)
            {
            //Do normal textbox for non-association field
                txt_fields += create_html_for_text_field(curr_col_model.index + 
                    "_field", curr_col_model.index, curr_col_model.width);
            }
            else
            {
                txt_fields += create_html_for_cmb(curr_col_model.index + 
                    "_field", curr_col_model.index, possible_values_for_assocs[curr_col_model.index]);
            }
            txt_fields += "</div>";
        }
        txt_fields += "</fieldset><div style=\"clear: both\"></div>";
        $("#details_form_fields").html(txt_fields);
        // prepare Options Object
        details_form_options = {
            url:        '',
            dataType: 'json',
            success:    function() {
                alert('Changes submitted!');
            }
        };

        
        $("#save_new_form_btn").click(function(e) {
            // stop normal link click
            e.preventDefault();
            $('#details_form').ajaxSubmit(prepare_options_for_form('Create',
              'Record created succesfully!'));
        });
        
        $("#save_form_btn").click(function(e) {
            // stop normal link click
            e.preventDefault();
            $('#details_form').ajaxSubmit(prepare_options_for_form(
            "Edit/" + _curr_selected_record_id,
              'Record saved succesfully!'));
        });
        
        $("#save_form_multiple_btn").click(function(e) {
            // stop normal link click
            e.preventDefault();
            var crud_model_id  = -1;
            var selected_ids = get_ids_of_selected_records();
            
            $('#ids_to_change').val(selected_ids.join(','));
            details_form_options.url = "EditMultiple";
            details_form_options.success =  function() {
                reset_grid_and_form('Records saved succesfully!');
            };
            $('#details_form').ajaxSubmit(details_form_options);
        });
        
        $("#delete_btn").click(function(e) {
            e.preventDefault();
            
            var answer = confirm("Are you sure you want to delete the selected records?");
            
	        if (answer){
                    var crud_model_id  = -1;
                    var ids = get_ids_of_selected_records();
                    //var form = document.getElementById('crud_grid');
                    var ids_to_delete_field = document.getElementById('ids_to_delete');

                    ids_to_delete_field.value = ids.join(',');
                    details_form_options.url = "Delete";
                    details_form_options.success =  function() {
                        reset_grid_and_form('Records were deleted!');
                    };
                    $('#delete_form').ajaxSubmit(details_form_options);
	        }
        });
        }
        
        function get_ids_of_selected_records()
        {
            var ids = new Array();

            $(".cbox:checkbox:checked").each(function(){
                crud_model_id = this.id.replace("jqg_","");
                ids.push(crud_model_id);
            });
            return ids;
        }
        
        var _curr_selected_record_id = -1;
        function show_record_in_form(crud_model_id)
        {
            _curr_selected_record_id = crud_model_id;
            var row_data = $("#list").getRowData(crud_model_id);
            for(var col_idx = 0; col_idx < col_model.length; col_idx++)
            {
                col_value = row_data[col_model[col_idx].name];
                col_field_id = col_model[col_idx].index + "_field";
                $("#"+col_field_id).val($.trim(col_value));
            }
        }
        
        function prepare_options_for_form(url, message_when_success)
        {
        
            details_form_options.url = url;
            details_form_options.success =  function(response_json) {
            
                $(".input-validation-error").removeClass("input-validation-error");
                $("#error_messages").empty();
               // response_json = eval("(" + response_json + ")" );
                if (response_json.type == "Error")
                {
                    //Display the error message in each field
                    violations = response_json.violations;
                    err_html = "<p>The following errors ocurred:</p><ul>";
                    for(var violation_idx = 0; violation_idx < violations.length; 
                    violation_idx++)
                    {
                        err_html += "<li>" +
                        violations[violation_idx].ErrorMessage + "</li>" ;
                        $("#" + violations[violation_idx].PropertyName
                        + "_field").addClass("input-validation-error");
                    }
                    $("#error_messages").html(err_html + "</ul>");
                }
                else
                {
                    reset_grid_and_form(message_when_success);
                }
            };
            return details_form_options;
        }
    </script>

    <script type="text/javascript" src="<%= PathResolver.GetSiteRoot() + "Scripts/jquery.jqGrid.js" %>"></script>
    <script type="text/javascript" src="<%= PathResolver.GetSiteRoot() + "Scripts/jquery.form.js" %>"></script>
    <h2>
        Create, Update, List and Delete
        <%= Model.grid_title %></h2>
    <form id="details_form" action="#" method="post">
    <div class="validation-summary-errors" id="error_messages">
    </div>
    <div id="details_form_fields">
    </div>
    <input type="hidden" value="" id="ids_to_change" name="ids_to_change" />
    <input type="reset" value="Clear the Form" />
    |
    <button id="save_new_form_btn" name="SaveNewForm">
        Save as New Record</button>
    |
    <button id="save_form_btn" name="SaveForm">
        Save to Current Record</button>
    <button id="save_form_multiple_btn" name="SaveMultipleForm">
        Save to Selected Records</button>
    </form>
    <form id="crud_grid" action="delete" method="get">
    <table id="list" class="scroll">
    </table>
    <div id="pager" class="scroll" style="text-align: center;">
    </div>
    </form>
    <form id="delete_form" action="delete" method="post">
    <input type="hidden" name="ids_to_delete" id="ids_to_delete" />
    <button id="delete_btn">
        Delete All the Selected Records</button>
    </form>
    <div id="crud_operation_output">
    </div>
</asp:Content>
